package com.usefullc.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usefullc.common.constants.SubPubConstants;
import com.usefullc.common.user.OnlineUser;
import com.usefullc.common.user.OnlineUserManager;
import com.usefullc.system.service.AbstractBizService;
import com.usefullc.system.service.MessagePublishService;
import com.usefullc.user.domain.AuthRes;
import com.usefullc.user.domain.Role;
import com.usefullc.user.mapper.RoleMapper;
import com.usefullc.user.param.RoleAuthResParam;
import com.usefullc.user.query.RoleQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: Sampson
 * @date: 2022-01-10 14:10
 */
@Service
public class RoleService extends AbstractBizService<RoleMapper,Role,RoleQuery> {

    @Autowired
    private MessagePublishService messagePublishService;

    @Override
    protected QueryWrapper<Role> getQueryWrapper(RoleQuery query) {
        QueryWrapper<Role> queryWrapper = super.getQueryWrapper(query);
        OnlineUser loginUser = OnlineUserManager.getLoginUser();
        if(loginUser != null && loginUser.getTenantId() != 0L){
            query.setTenantId(loginUser.getTenantId());
        }
        return queryWrapper;
    }

    @Transactional
    public void saveRoleAuthRes(RoleAuthResParam param){
        //先删除旧的中间表
        this.getBaseMapper().deleteRoleAuthResByRoleId(param.getRoleId());

        this.getBaseMapper().insertRoleAuthResBatch(param);

        //必须重新初始化权限资源
        messagePublishService.publish(SubPubConstants.AUTH_DATA);

    }
}
